package com.esm.sm800.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.esm.sm800.R;
import com.esm.sm800.database.dbmodel.Needle;
import com.esm.sm800.database.manager.NeedleCenter;
import com.esm.sm800.database.manager.SystemCenter;
import com.esm.sm800.util.Camera2Manager;
import com.esm.sm800.util.Utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.ui.BottomMenuWindow;
import zuo.biao.library.util.EditTextUtil;

//针组编辑
public class ZzbjActivity extends BaseActivity implements View.OnClickListener {

    private final String TAG = "ZzbjActivity";

    private TextView tv_ks;
    private TextView tv_zhijin;
    private EditText et_name;

    private TextView tv_cw;
    private TextView tv_len;
    private TextView tv_cl;

    ImageView iv_pic;

    EditText et_yjz;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_zzbj);

        tv_ks = (TextView) findViewById(R.id.tv_ks);
        tv_zhijin = (TextView) findViewById(R.id.tv_zhijin);
        et_name = (EditText) findViewById(R.id.et_name);
        tv_cw = (TextView) findViewById(R.id.tv_cw);
        tv_len = (TextView) findViewById(R.id.tv_len);
        tv_cl = (TextView) findViewById(R.id.tv_cl);
        et_yjz = (EditText) findViewById(R.id.et_yjz);
        iv_pic = (ImageView) findViewById(R.id.iv_pic);

        et_name.setFocusable(false);
        et_yjz.setFocusable(false);

        findViewById(R.id.tv_back).setOnClickListener(this);
        findViewById(R.id.tv_save).setOnClickListener(this);
        findViewById(R.id.tv_ks).setOnClickListener(this);
        findViewById(R.id.tv_zhijin).setOnClickListener(this);
        findViewById(R.id.tv_cjcd).setOnClickListener(this);
        findViewById(R.id.et_name).setOnClickListener(this);
        findViewById(R.id.et_yjz).setOnClickListener(this);
        findViewById(R.id.bt_xgtp).setOnClickListener(this);


        if (SystemCenter.getInstance().needleEdit == null) {
            SystemCenter.getInstance().needleEdit = new Needle();
        } else {
            String imagePath = "" + SystemCenter.getInstance().needleEdit.getImg();
            // 使用BitmapFactory解码图片文件
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            if (bitmap != null) {
                iv_pic.setImageBitmap(bitmap);
            }
        }

        et_name.setText(SystemCenter.getInstance().needleEdit.getName());

        String[] KS_NAMES = getResources().getStringArray(R.array.zks_names);
        int pos = SystemCenter.getInstance().needleEdit.getKuanshi();
        if (pos >= 0 && pos < KS_NAMES.length) {
            tv_ks.setText(KS_NAMES[pos]);
            tv_ks.requestFocus();
        }
        tv_zhijin.setText(SystemCenter.getInstance().needleEdit.getZhijing() + "");
        tv_cw.setText(getString(R.string.weizhi_title) + SystemCenter.getInstance().needleEdit.getPosition() + "");
        tv_len.setText(SystemCenter.getInstance().needleEdit.getLength() + "");
        tv_cl.setText(SystemCenter.getInstance().needleEdit.getStock() + "");
        et_yjz.setText(SystemCenter.getInstance().needleEdit.getWarning_num() + "");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public static final int REFRESH_UI = 1101;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == REFRESH_UI) {

            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.tv_ks:
                onKS();
                break;
            case R.id.tv_zhijin:
                onZhijin();
                break;
            case R.id.tv_save:
                onSave();
                break;
            case R.id.tv_cjcd:
                onCjcd();
                break;
            case R.id.et_name:
                EditTextUtil.showKeyboard(context, et_name, true);
                break;
            case R.id.et_yjz:
                EditTextUtil.showKeyboard(context, et_yjz, true);
                break;
            case R.id.bt_xgtp:
                onXgtp();
                break;
        }
    }

    private void onXgtp() {
        Intent pictureSelectIntent = new Intent(Intent.ACTION_PICK);//设置Action
        pictureSelectIntent.setType("image/");//设置数据的类型
        startActivityForResult(pictureSelectIntent, 111);
    }

    private void onCjcd() {
        if (Utils.isFastDoubleClick()) {
            return;
        }
        SystemCenter.getInstance().needlelen = 0;
        Intent intent = new Intent(this, JzsbceActivity.class);
        startActivityForResult(intent, 66);
    }

    private void onSave() {
        if (Utils.isFastDoubleClick()) {
            return;
        }
        try {
            int len = Integer.parseInt(tv_len.getText().toString());
            int stock = Integer.parseInt(tv_cl.getText().toString());
            int warningnum = Integer.parseInt(et_yjz.getText().toString());
            String name = et_name.getText().toString();
            SystemCenter.getInstance().needleEdit.setName(name);
            SystemCenter.getInstance().needleEdit.setLength(len);
            SystemCenter.getInstance().needleEdit.setStock(stock);
            SystemCenter.getInstance().needleEdit.setWarning_num(warningnum);

            NeedleCenter.getInstance().saveNeedle(SystemCenter.getInstance().needleEdit);
        } catch (Exception e) {
            showShortToast(getString(R.string.cwdsz));
            return;
        }
        setResult(RESULT_OK);
        finish();
    }

    private void onKS() {
        toActivity(BottomMenuWindow.createIntent(getBaseContext(), getResources().getStringArray(R.array.zks_names))
                .putExtra(BottomMenuWindow.INTENT_TITLE, getString(R.string.zks_title)), REQUEST_TO_BOTTOM_MENU_1, false);

    }

    public static String[] ZHIJING_NAMES = {"10", "11", "12", "13", "14", "15", "16"};

    private void onZhijin() {
        toActivity(BottomMenuWindow.createIntent(getBaseContext(), ZHIJING_NAMES)
                .putExtra(BottomMenuWindow.INTENT_TITLE, getString(R.string.zhijin_titlte)), REQUEST_TO_BOTTOM_MENU_2, false);

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private final int REQUEST_TO_BOTTOM_MENU_1 = 31;
    private final int REQUEST_TO_BOTTOM_MENU_2 = 32;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        et_name.clearFocus();
        et_yjz.clearFocus();

        switch (requestCode) {
            case REQUEST_TO_BOTTOM_MENU_1:
                if (data != null) {
                    int pos = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    String[] KS_NAMES = getResources().getStringArray(R.array.zks_names);
                    if (pos >= 0 && pos < KS_NAMES.length) {
                        SystemCenter.getInstance().needleEdit.setKuanshi(pos);
                        tv_ks.setText(KS_NAMES[pos]);
                        tv_ks.requestFocus();
                    }
                }
                break;
            case REQUEST_TO_BOTTOM_MENU_2:
                if (data != null) {
                    int pos = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    if (pos >= 0 && pos < ZHIJING_NAMES.length) {
                        String zhijin = ZHIJING_NAMES[pos];
                        try {
                            int zj = Integer.parseInt(zhijin);
                            SystemCenter.getInstance().needleEdit.setZhijing(zj);
                            tv_zhijin.setText(ZHIJING_NAMES[pos]);
                            tv_zhijin.requestFocus();
                        } catch (Exception e) {

                        }
                    }
                }
                break;
            case 66:
                tv_len.setText(SystemCenter.getInstance().needlelen + "");
                break;
        }

        if (requestCode == 111) {
            Uri imageUri = data.getData();//得到图片的路径
            InputStream imageStream;//得到基于路径的流文件
            try {
                imageStream = getContentResolver().openInputStream(imageUri);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
            //305x146
            Bitmap orgImage = BitmapFactory.decodeStream(imageStream);//原始图片
            int w = orgImage.getWidth();
            int h = orgImage.getHeight();
            if (w <= 305) {
                saveBitmapToFile(orgImage);
            } else {
                int xsale = (int) (w / 305);
                Bitmap selectImage = Utils.scaleBitmap(orgImage, w / xsale, h / xsale);
                saveBitmapToFile(selectImage);

                if (orgImage != null && !orgImage.isRecycled()) {
                    orgImage.recycle();
                    orgImage = null;
                }
            }
        }

    }

    public void saveBitmapToFile(Bitmap bitmap) {
        if (bitmap == null) {
            return;
        }

        String needlename = et_name.getText().toString();

        String path = Camera2Manager.get().getFilesPath(context) + "/ZZJPG/";
        File dir = new File(path);
        boolean isok = false;
        if (!dir.exists()) {
            isok = dir.mkdirs();
        }

        int w0 = bitmap.getWidth();
        int h0 = bitmap.getHeight();

        //305x146
        int w = w0;
        int h = h0;
        if (w > 305) {
            w = 305;
        }
        if (h > 146) {
            h = 146;
        }
        Bitmap selectImage = Bitmap.createBitmap(bitmap, 0, 0, w, h);
        iv_pic.setImageBitmap(selectImage);

        //保存图片
        String imageFileName = needlename + ".jpg";
        String hzJpgpath = path + imageFileName;
        SystemCenter.getInstance().needleEdit.setImg(hzJpgpath);

        File outputFile = new File(path, imageFileName);
        try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
            // 压缩Bitmap到指定输出流中
            // 第一个参数是压缩格式（Bitmap.CompressFormat），这里使用JPEG
            // 第二个参数是压缩质量，范围是0（最低质量，文件最小）到100（最高质量，文件最大）
            selectImage.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            // 确保数据写入输出流
            outputStream.flush();
            // 成功保存后可以在这里做一些操作，比如通知用户或更新UI
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常，比如显示错误消息或记录日志
        }

        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }

    }


    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }
}
